package com.itheima.easy.handler.aliyun;

import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.app.models.AlipayTradeAppPayResponse;
import com.itheima.easy.constant.SuperConstant;
import com.itheima.easy.constant.TradeConstant;
import com.itheima.easy.enums.TradeEnum;
import com.itheima.easy.exception.ProjectException;
import com.itheima.easy.handler.AppPayHandler;
import com.itheima.easy.utils.EmptyUtil;
import com.itheima.easy.utils.ExceptionsUtil;
import com.itheima.easy.vo.TradeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @ClassName AliAppPayHandler.java
 * @Description 原生APP支付处理
 */
@Slf4j
@Component
public class AliAppPayHandler extends AliCommonPayHandler implements AppPayHandler {

    @Override
    public TradeVo appTrade(TradeVo tradeVo) {
        //1、获得支付宝配置文件
        Config config = aliPayConfig.config();
        //2、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new ProjectException(TradeEnum.CONFIG_ERROR);
        }
        //3、使用配置
        Factory.setOptions(config);
        try {
            AlipayTradeAppPayResponse appPayResponse = Factory.Payment
                .App().pay(tradeVo.getMemo(),
                    String.valueOf(tradeVo.getTradeOrderNo()),
                    String.valueOf(tradeVo.getTradeAmount()));
            //4、检查网关响应结果
            boolean isSuccess = ResponseChecker.success(appPayResponse);
            //5、网关响应成功且appPayResponse有返回结果
            if (isSuccess&&!EmptyUtil.isNullOrEmpty(appPayResponse.getBody())){
                tradeVo.setIsRefund(SuperConstant.NO);
                tradeVo.setPlaceOrderCode(TradeConstant.ALI_SUCCESS_CODE);
                tradeVo.setPlaceOrderMsg(TradeConstant.ALI_SUCCESS_MSG);
                tradeVo.setPlaceOrderJson(appPayResponse.getBody());
                tradeVo.setTradeState(TradeConstant.TRADE_WAIT_BUYER_PAY);
                return tradeVo;
            }else {
                log.error("网关：支付宝APP统一下单：{},结果：{}", tradeVo.getTradeOrderNo(),
                    JSONObject.toJSONString(appPayResponse));
                throw new RuntimeException("网关：支付宝APP统一下单创建失败!");
            }
        } catch (Exception e) {
            log.error("支付宝APP统一下单创建失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(TradeEnum.PAYING_TRADING_FAIL);
        }
    }
}
